
import sys
from PyQt4 import Qt
from PyQt4.phonon import Phonon
import os
import stagger
from TrayIcon import SystemTrayIcon
from Database import *
from Settings import *
from Widgets import *
from form.DialogForm import *
__version__ = "1.0.0"




from form.OptionsForm import *
class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        '''
        tworzenie gui, ustawien, odtwarzacza,ikon.
        Laczenie ze zdarzeniami
        '''
        super(MainWindow, self).__init__()

        try: os.mkdir(Settings.configDir)
        except : print("MainWindow: Config directory already exist")
        self.settings=Settings()
        self.database = Database()
        print (self.settings.libraryDirectories)
        
        ###
        ###    Tray
        ###
        self.icon=SystemTrayIcon()
        self.icon.activated.connect(self.activate)


        ######
        ######    GUI
        ######
        self.treeWidget= TreeWidget()
        self.fileWidget = TableWidget(0, 7)
        self.audioPlay = AudioPlayer()
        self.fileWidget.audioPlay=self.audioPlay
        
        self.genreWidget=ListWidget('genre')
        self.artistWidget=ListWidget('artist')
        self.albumWidget=ListWidget('album')

        vBoxFileAndPlay = QtGui.QVBoxLayout()
        vBoxFileAndPlay.addWidget(self.fileWidget)
        vBoxFileAndPlay.addWidget(self.audioPlay)

        hBoxFilters = QtGui.QHBoxLayout()
        hBoxFilters.addWidget(self.genreWidget)
        hBoxFilters.addWidget(self.artistWidget)
        hBoxFilters.addWidget(self.albumWidget)

        filters=QtGui.QGroupBox()
        filters.setLayout(hBoxFilters)

        #2 to Qt.Vertical ktore nie dzialalo
        self.messageSplitter = QtGui.QSplitter(2) 
        
        self.messageSplitter.addWidget(filters)

        self.fileAndPlay = QtGui.QGroupBox()
        self.fileAndPlay.setLayout(vBoxFileAndPlay)
        self.messageSplitter.addWidget(self.fileAndPlay)
        
        self.mainSplitter = QtGui.QSplitter()
        self.mainSplitter.addWidget(self.treeWidget)
        self.mainSplitter.addWidget(self.messageSplitter)

        self.setCentralWidget(self.mainSplitter)

        self.mainSplitter.setStretchFactor(0, 1)
        self.mainSplitter.setStretchFactor(1, 3)

        self.messageSplitter.setStretchFactor(0, 1)
        self.messageSplitter.setStretchFactor(1, 2)

        self.createMenusAndToolbars()

        self.refreshWidgets()
        
        self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)
        #self.artistWidget.wypelnijArtist()
        #self.albumWidget.wypelnijAlbum()
        status = self.statusBar()
        status.setSizeGripEnabled(False)
        status.showMessage("Ready", 5000)
        self.setWindowTitle('PyMP - Python Music Player')

    def refreshWidgets(self):
        '''
        odswierza wartosci wszystkich widzetow
        '''
        TreeWidget.instance.refreshTreeValues()
        ListWidget.wypelnij()
        ListWidget.currentItemChanged(self)
    def createMenusAndToolbars(self):
        '''
        tworzenie menu
        '''
        fileMenu = self.menuBar().addMenu("&Plik")
        editMenu = self.menuBar().addMenu("&Edycja")
        
        openOptionsAction = QtGui.QAction(QtGui.QIcon('icons/oxygen/openOptions.png'), '&Opcje', self)
        openOptionsAction.setShortcut('Ctrl+P')
        openOptionsAction.setStatusTip('Opcje programu')
        openOptionsAction.triggered.connect(self.optionsForm)

        
        openFolderAction = QtGui.QAction(QtGui.QIcon('icons/oxygen/openFolder.png'), '&Otworz folder', self)
        openFolderAction.setShortcut('Ctrl+O')
        openFolderAction.setStatusTip('Otwiera i dodaje folder do bazy')
        openFolderAction.triggered.connect(self.showOpenFolderDialog)

        btnRefreshDatabase = QtGui.QAction(QtGui.QIcon('icons/oxygen/refreshDatabase.png'), '&Odswierz baze danych', self)
        btnRefreshDatabase.setShortcut('Ctrl+R')
        btnRefreshDatabase.setStatusTip('Odswierz baze danych')
        btnRefreshDatabase.triggered.connect(self.refreshDatabse)
        
        btnCleanDatabase = QtGui.QAction(QtGui.QIcon('icons/oxygen/cleanDatabase.png'), '&Wyczysc baze', self)
        btnCleanDatabase.setShortcut('Ctrl+T')
        btnCleanDatabase.setStatusTip('Wyczysc baze danych')
        btnCleanDatabase.triggered.connect(self.cleanDatabase)


        #openFileAction = QtGui.QAction(QtGui.QIcon('icons/oxygen/openFile.png'), '&Open File', self)
        #openFileAction.setShortcut('Ctrl+I')
        #openFileAction.setStatusTip('Open File')
        #openFileAction.triggered.connect(self.showOpenFileDialog)


        exitAction = QtGui.QAction(QtGui.QIcon('icons/oxygen/exit.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Wyjdz')
        exitAction.triggered.connect(QtGui.qApp.quit)
        
        savePlaylistsAction = QtGui.QAction(QtGui.QIcon('icons/oxygen/exit.png'), '&Save playlists', self)
        savePlaylistsAction.setShortcut('Ctrl+S')
        savePlaylistsAction.triggered.connect(self.savePlaylists)
        
        readPlaylistsAction = QtGui.QAction(QtGui.QIcon('icons/oxygen/exit.png'), '&Read playlists', self)
        readPlaylistsAction.setShortcut('Ctrl+W')
        readPlaylistsAction.triggered.connect(self.readPlaylists)
        
        
        openMenu = fileMenu.addMenu('&Otworz')
        openMenu.addAction(openFolderAction)
        fileMenu.addAction(btnRefreshDatabase)
        fileMenu.addAction(btnCleanDatabase)
        fileMenu.addSeparator()
        fileMenu.addAction(openOptionsAction)
        fileMenu.addSeparator()
        fileMenu.addAction(exitAction)
        fileMenu.addAction(savePlaylistsAction)
        fileMenu.addAction(readPlaylistsAction)
        editMode = QtGui.QAction(QtGui.QIcon('editModeOn.png'), '&Edit mode', self)
        editMode.setShortcut('Ctrl+e')
        editMode.setStatusTip('Edytowanie')
        editMode.triggered.connect(self.editMode)

        editMenu.addAction(editMode)
    def readPlaylists(self):
        TreeWidget.instance.readPlaylists()
    def savePlaylists(self):
        print ("saving pls")    
        name, ok = QtGui.QInputDialog.getText(self, 'Playlist name', 
            'Please enter playlist name:')
        if ok:
            print (TreeWidget.instance.current)
            if not os.path.exists(Settings.instance.playlistsDirectory):
                os.makedirs(Settings.instance.playlistsDirectory)
    
            with open(Settings.instance.playlistsDirectory+name+".m3u", 'w') as file:
                for item in TreeWidget.instance.current:
                    file.write("{}\n".format(item))
        self.readPlaylists()
    def refreshDatabse(self):
        '''
        Odswierza baze danych.
        Odswierza widzety po odswierzeniu bazy danych
        '''
        Database.refreshDatabase(Database.instance)
        self.refreshWidgets()
    def cleanDatabase(self):
        '''
        Czysci baze danych
        '''
        Database.cleanDatabase(Database.instance)
        self.refreshWidgets()
        
    def editMode(self):
        '''
        zmienia editmode
        '''
        if Settings.editState == False:
            Settings.editState=True
        else: Settings.editState=False

    def optionsForm(self):
        '''
        wywoluje okno ustawien
        '''
        dialog = OptionsForm()
        dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        dialog.exec_()
    def showOpenFileDialog(self):
        '''
        okno dialogowe wybierania pliku
        '''
        file = OpenFolderDialog()
        if file.exec_() == 1: 
            print (file.selectedFiles())
        
    def showOpenFolderDialog(self):
        
        '''
        okno dialogowe wybierania folderu
        odswierzanie widzetow
        '''
        directory = OpenFolderDialog()
        directory.setFileMode(Qt.QFileDialog.DirectoryOnly)
        if directory.exec_() == 1: 
            folder = directory.selectedFiles()[0]
            if (folder[-1]!="/"):
                folder+="/"
            Settings.addDirectory(Settings.instance,folder)
            self.refreshWidgets()
        

  
    def closeEvent(self, event):
        '''
        Chowanie okna i pokazywanie ikonki
        '''
        self.icon.show()
        self.hide()
        event.ignore()      
    def activate(self,reason ):
        '''
        przy dwukliku chowa ikonke i uaktywnia glowne okno
        '''
        print (reason )
        if reason==2:
            self.show()
            self.icon.hide()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)    
    app.setOrganizationName('PyMP')
    app.setApplicationName("PyMp - Python Music Player")
    form = MainWindow()
    form.show()
    app.exec_()





